const {
  getUserList,
  getUserCount,
  addUser,
  updateUser,
  deleteUser
} = require('../service/user.service');
const { judgeIfMissParam } = require('../utils/common');

class UserController {
  // 获取用户列表
  async getUserList(ctx, next) {
    let page = ctx.query.page || 1;
    let size = ctx.query.size || 10;
    const requiredArr = ['page', 'size', 'name', 'identify'];
    const flag = judgeIfMissParam(ctx, '[user.controller_getUserList]', requiredArr, ctx.query);
    if (!flag) return;

    let options = {
      page: ((page - 1) * size).toString(),
      size: size.toString(),
      name: ctx.query.name,
      identify: ctx.query.identify
    };

    const result = await getUserList(options);
    const total = await getUserCount();

    ctx.body = {
      ret: 0,
      data: {
        list: result,
        total,
        page,
        size
      }
    }
  }

  // 新增用户
  async addUser(ctx, next) {
    const requireArr = ['name', 'phone', 'address'];
    const flag = judgeIfMissParam(ctx, '[user.controller_addUser]', requireArr, ctx.request.body);
    if (!flag) return;

    let options = {
      ...ctx.request.body,
      identify: 'MU' + new Date().getTime(),
      valid: 1
    }
    if (!('age' in options)) options.age = 0;
    if (!('sex' in options)) options.sex = 2;
    const result = await addUser(options);
    if (!result) return;
    ctx.body = {
      ret: 0,
      data: 'ok'
    }
  }

  // 
  async updateUser(ctx, next) {
    const requiredArr = ['id', 'address', 'phone'];
    const flag = judgeIfMissParam(ctx, '[user.controller_updateUser]', requiredArr, ctx.request.body);
    if (!flag) return;

    const result = await updateUser(ctx.request.body);
    if (!result) return;
    ctx.body = {
      ret: 0, 
      data: 'ok'
    }
  }

  // 失效用户接口
  async deleteUser(ctx, next) {
    const requireArr = ['id'];
    const flag = judgeIfMissParam(ctx, '[user.controller_deleteUser]', requireArr, ctx.query);
    if (!flag) return;

    const result = await deleteUser(ctx.query);
    if (!result) return;
    ctx.body = {
      ret: 0,
      data: 'ok'
    }
  }
}

module.exports = new UserController();